package org.leonos.web.system.controller;

import com.jfinal.core.Controller;
import org.leonos.core.annotation.Check;
import org.leonos.core.common.Const;
import org.leonos.utils.PageCreator;
import org.leonos.utils.Utils;
import org.leonos.web.system.model.Menu;
import org.leonos.web.system.model.User;

import java.util.List;

/**
 * 系统管理 -> 菜单管理
 * @author LeonXiao
 */
public class MenuController extends Controller{

    private static Object obj = new Object();

    private static final String menuPage = "/WEB-INF/view/base/menu/menu.jsp";
    private static final String menuEditPage = "/WEB-INF/view/base/menu/menu_edit.jsp";
    private static final String menuAddPage = "/WEB-INF/view/base/menu/menu_add.jsp";

    /**
     * 菜单管理
     */
    @Check(isLogin = true)
    public void index() {
        User user = getSessionAttr(Const.LOG_USER);
        setAttr("menusInPanel", PageCreator.createMenusInPanelByUser(user));
        render(menuPage);
    }

    /**
     * 菜单编辑
     */
    @Check(isLogin = true)
    public void editMenu() throws Exception {
        String menuid = getPara("menuid");
        Menu menu = Menu.dao.findById(menuid);
        if (menu == null) throw new Exception("未找到相应菜单");
        setAttr("menu", menu);

        List<Menu> subMenus = Menu.dao.findSubMenu(menuid);
        setAttr("subMenus", subMenus.size() == 0 ? "- - -" : Utils.getMenusToString(subMenus));

        String parMenuName = Menu.dao.findById(menu.getStr("pid")).getStr("name");
        setAttr("parMenus", parMenuName);

        render(menuEditPage);
    }

    /**
     * 添加菜单
     */
    @Check(isLogin = true)
    public void addMenu() throws Exception {
        String pid = getPara("pid");
        setAttr("pid", pid);
        setAttr("parMenus", "后台管理系统");
        setAttr("subMenus", "- - -");

        String defaultPid = Menu.dao.findByPermissions(Const.MANGE_MENU).getStr("id"); // 默认使用根目录
        setAttr("sort", Menu.dao.getSort(defaultPid));

        if (pid != null) {
            String parMenuName = Menu.dao.findById(pid).getStr("name");
            setAttr("parMenus", parMenuName);
            setAttr("sort", Menu.dao.getSort(pid));
        }
        render(menuAddPage);
    }

}
